var Promise = require('es6-promise.min.js')

function wxPromisify(fn) {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        //成功 
        resolve(res)
      }
      obj.fail = function(res) {
        //失败 
        reject(res)
      }
      fn(obj)
    })
  }
}

//无论promise对象最后状态如何都会执行 
Promise.prototype.finally = function(callback) {
  let P = this.constructor;
  return this.then(value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => {
    throw reason
  }));
};

function wxLogin() {
  return wxPromisify(wx.login)
}

function wxGetUserInfo() {
  return wxPromisify(wx.getUserInfo)
}

function wxGetSystemInfo() {
  return wxPromisify(wx.getSystemInfo)
}

module.exports = {
  wxPromisify: wxPromisify,
  wxLogin: wxLogin,
  wxGetUserInfo: wxGetUserInfo,
  wxGetSystemInfo: wxGetSystemInfo
}